package cn.edu.cug.cs.gtl.docsrv.auth.service.imp;

import cn.edu.cug.cs.gtl.docsrv.auth.dao.LoginDao;
import cn.edu.cug.cs.gtl.docsrv.auth.service.LoginService;
import cn.edu.cug.cs.gtl.docsrv.config.Configuration;
import cn.edu.cug.cs.gtl.mybatis.mapper.auth.AuthUser;
import cn.edu.cug.cs.gtl.mybatis.mapper.auth.Authority;
import cn.edu.cug.cs.gtl.mybatis.metadata.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class LoginServiceImpl implements LoginService {
    @Autowired
    LoginDao loginDao;

    @Override
    public boolean checkUser(AuthUser authUser) throws Exception{
        String userName = authUser.getUserName();
        AuthUser fromDB=null;
        if(userName==null || userName.isEmpty()){
            fromDB = loginDao.getUser(userName);
        }
        else{
            fromDB = loginDao.getUser(authUser.getUserInternalId().longValue());
        }

        if(fromDB==null){
            return false;
        }
        else{
            if(fromDB.getUserPassword().equals(authUser.getUserPassword())) {
                Authority authority = AuthUtils.getAuthority(userName);
                Configuration.setAuthority(authority);
                return true;
            }
            else
                return false;
        }
    }

    @Override
    public boolean checkUser(String userName, String password) throws Exception {
         AuthUser fromDB=loginDao.getUser(userName);
         if(fromDB.getUserPassword().equals(password)) {
             Authority authority = AuthUtils.getAuthority(userName);
             Configuration.setAuthority(authority);
             return true;
         }
         else return false;
    }
}
